# Copyright 2023 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import os
import time

from pydub import AudioSegment


def check_args(args):
    if not os.path.exists(args.audio_path):
        raise ValueError(f"Audio file {args.audio_path} does not exist.")
    if args.segment_length_ms <= 0:
        raise ValueError(f"Segment length must be greater than 0. Got {args.segment_length_ms}.")
    if args.sample_rate <= 0:
        raise ValueError(f"Sample rate must be greater than 0. Got {args.sample_rate}.")
    if args.num_channels <= 0:
        raise ValueError(f"Number of channels must be greater than 0. Got {args.num_channels}.")


def split_audio(args):
    check_args(args)
    os.makedirs(args.output_dir, exist_ok=True)
    audio = AudioSegment.from_file(args.audio_path)

    # check if the audio is too short
    if len(audio) < args.segment_length_ms:
        print("Warning: Audio is too short. No segmentation is required.")
        return

    # Add two silence segments at the end of the audio to simulate the end of a speech.
    audio += AudioSegment.silent(duration=2 * args.segment_length_ms)

    if audio.channels != 1:
        print("Warning: Audio has more than 1 channel. Stereo to mono conversion is required.")
        audio = audio.set_channels(1)

    if audio.frame_rate != args.sample_rate:
        print(f"Warning: Audio has a frame rate of {audio.frame_rate}. Resampling to {args.sample_rate}.")
        start = time.time()
        audio = audio.set_frame_rate(args.sample_rate)
        print(f"Resampling took {(time.time() - start) * 1000} ms.")

    # Calculate the number of segments
    num_segments = len(audio) // args.segment_length_ms

    # Split the audio into segments
    for i in range(num_segments):
        start_time = i * args.segment_length_ms
        end_time = (i + 1) * args.segment_length_ms
        segment = audio[start_time:end_time]

        # Save each segment to a new file
        output_file = f"segment_{str(i + 1).zfill(3)}.wav"
        output_file = os.path.join(args.output_dir, output_file)
        segment.export(output_file, format="wav")


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--audio_path', required=True, help='input audio file')
    parser.add_argument('--output_dir', required=True, help='output dir for audio segments')
    parser.add_argument('--segment_length_ms', type=int, default=500, help='segment length in ms')
    parser.add_argument('--sample_rate', type=int, default=16000, help='sample rate')
    parser.add_argument('--num_channels', type=int, default=1, help='number of channels')
    args = parser.parse_args()
    return args


if __name__ == "__main__":
    opt = parse_args()
    split_audio(opt)
